/*
 * Copyright (c) 2006-2025, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-03-08     RT-Thread    first version
 */

#include <rtthread.h>

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#include <rtdevice.h>
#include "board.h"
#include "stm32l431xx.h"
#include "rt-thread\components\drivers\include\drivers\pm.h"

#define PM_INT_PIN GET_PIN(A, 0) // 定义 PM 中断引脚为 PA0

void PM_int_callback(void *args)
{

    rt_kprintf("PM Data Ready Interrupt Triggered!\n");
}

void PM_int_init(void)
{
    // 设置 PA0 为输入模式

    rt_kprintf("PM INT pin init\r\n");
    rt_pin_mode(PM_INT_PIN, PIN_MODE_INPUT_PULLUP);

    // 绑定中断回调函数
    rt_pin_attach_irq(PM_INT_PIN, PIN_IRQ_MODE_RISING, PM_int_callback, RT_NULL);

    // 使能中断
    rt_pin_irq_enable(PM_INT_PIN, PIN_IRQ_ENABLE);
}

INIT_BOARD_EXPORT(PM_int_init);

#define LED_1 GET_PIN(C, 1) // LED1引脚定义
void pm_notify(rt_uint8_t event, rt_uint8_t mode, void *data)
{
    if (event == RT_PM_ENTER_SLEEP && mode == PM_SLEEP_MODE_DEEP) // 进入睡眠
    {
        rt_pin_write(LED_1, PIN_HIGH);
        rt_kprintf("enter pm\n");
    }
    else if (event == RT_PM_EXIT_SLEEP && mode == PM_SLEEP_MODE_DEEP) // 退出休眠
    {
        rt_pm_dump_status(); // 打印 PM 组件的状态
        rt_pm_run_enter(PM_RUN_MODE_HIGH_SPEED);
        clock_information();               // 打印时钟频率
        rt_pm_release(PM_SLEEP_MODE_DEEP); // 释放 DeepSleep 模式
        rt_pm_request(PM_SLEEP_MODE_NONE); // 请求工作模式

        rt_pin_write(LED_1, PIN_LOW);
    }
}

int stop_mode_test(void)
{
    rt_pm_request(PM_SLEEP_MODE_DEEP); // 请求 stop 模式
    rt_pm_dump_status();               // 打印 PM 组件状态
    rt_pm_release(PM_SLEEP_MODE_NONE); // 释放正常工作模式，释放后才能进入 stop 模式
    rt_pm_dump_status();               // 打印 PM 组件状态
    return 0;
}
MSH_CMD_EXPORT(stop_mode_test, stop_mode_test);

int main(void)
{

    clock_information();

    rt_pm_notify_set(pm_notify, 0);

    return RT_EOK;
}
